package com.lihang.rabbit1.common.page;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import java.io.Serializable;

/**
 * 分页请求参数封装
 */
@Data
@Schema(description = "分页请求参数")
public class PageReq implements Serializable {

    private static final long serialVersionUID = 1L;

    @Schema(description = "当前页码", defaultValue = "1")
    @Min(value = 1, message = "页码不能小于1")
    private long currentPage = 1;

    @Schema(description = "每页记录数", defaultValue = "10")
    @Min(value = 1, message = "每页记录数不能小于1")
    @Max(value = 100, message = "每页记录数不能大于100")
    private long pageSize = 10;

    @Schema(description = "排序字段")
    @Pattern(regexp = "^[a-zA-Z0-9_]*$", message = "排序字段只能包含英文、数字和下划线")
    private String orderField;

    @Schema(description = "排序方式，可选值：asc（升序）、desc（降序）", defaultValue = "desc")
    @Pattern(regexp = "^(asc|desc)$", message = "排序方式只能是asc或desc")
    private String orderType = "desc";

    /**
     * 转换为MyBatis Plus分页对象
     */
    public <T> Page<T> toPage() {
        Page<T> page = new Page<>(currentPage, pageSize);
        if (orderField != null && !orderField.isEmpty()) {
            if (orderType != null && orderType.equalsIgnoreCase("asc")) {
                page.addOrder(OrderItem.asc(orderField));
            } else {
                page.addOrder(OrderItem.desc(orderField));
            }
        }
        return page;
    }
}